<template>
  <div class="login">
    <el-form :model="form" :rules="rules" ref="form" class="form">
      <img class="logo" src="../../assets/common/login-logo.png" alt="" />
      <el-form-item prop="mobile">
        <el-input
          @keyup.enter.native="submit"
          prefix-icon="el-icon-user"
          v-model="form.mobile"
        ></el-input>
      </el-form-item>
      <el-form-item prop="password">
        <el-input
          show-password
          @keyup.enter.native="submit"
          prefix-icon="el-icon-lock"
          v-model="form.password"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button
          :loading="loginBtnLoading"
          @click="submit"
          class="submit"
          type="primary"
          >登录</el-button
        >
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { validatePhone } from '../../utils/validate'
export default {
  data () {
    return {
      loginBtnLoading: false, // login按钮加载
      // 表单数据
      form: {
        mobile: '13800000002',
        password: '123456'
      },
      // 表单规则, required是否必填, message未输入提示, validator自定义校验规则
      // trigger触发规则, blur焦点事件, change内容变化事件
      rules: {
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          {
            required: true,
            validator: (rule, value, callback) => {
              validatePhone(value)
                ? callback()
                : callback(new Error('请输入正确的手机号'))
            },
            trigger: 'blur'
          }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 12, message: '请输入6-12位密码', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    submit () {
      this.$refs.form.validate(async valid => {
        if (!valid) return
        // 发请求
        this.loginBtnLoading = true
        await this.$store.dispatch('user/getUserToken', this.form)
        this.loginBtnLoading = false
        let _redirect = this.$route.query.redirect
        if (_redirect) {
          this.$router.push(_redirect)
        } else {
          this.$router.push('/')
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.login {
  height: 100vh;
  background: url('../../assets/common/login.jpg');
  display: flex;
  justify-content: center;
  align-items: center;
  .form {
    width: 500px;
    text-align: center;
    .logo {
      padding-bottom: 20px;
    }
    .submit {
      width: 100%;
    }
  }
}
</style>
